<?php
/**
 * Created by PhpStorm.
 * User: Qch
 * Date: 2018/10/1
 * Time: 20:01
 */

namespace J\MVC;


use J\Schema\Artisan;
use J\Schema\Syntax;
use J\Intent;
use J\Message;

class Install
{
    /**
     * @param Module $module
     * @param Intent $intent
     * @return bool
     * @throws \J\Exception
     */
    public static function install(Module $module, Intent $intent)
    {
        $app = $module->getApp();

        $install = strtolower($intent->action) === 'install';

        // 必须是超级管理员
        if (!$app->User()->isAdministrator()) return false;
        // 创建SQL语句
        $sql = Artisan::start($module->getModels(), $install);
        // 执行安装/卸载
        $module->getApp()->Database()->create($sql);

        if ($install) self::insert($module, $intent);
        else self::erase($module, $intent);

        return true;
    }

    /**
     * @param Module $module
     * @param Intent $intent
     * @throws \J\Exception
     */
    protected static function insert(Module $module, Intent $intent)
    {
        $install = $module->get(Syntax::KEY_INSTALL, false);
        if (empty($install)) return;
        // 逐集合添加数据
        $values = array_isset($install, 'values', []);
        if (is_array($values)) foreach ($values as $collection => $rows)
            $module->insertValuesToCollection($collection, $rows);

        // 添加权限列表
        $resource = array_isset($install, Syntax::KEY_RESOURCE, false);
        if (!empty($resource)) $module->fetch('Resource', [
            'rows' => $resource, 'module' => $module->getName()]);
        // 主动跳转
        $next = array_isset($install, 'next', false);
        if ($next) $intent->jump($next);

        $intent->ajax(true, Message::INSTALL_SUCCESS);
    }

    protected static function erase(Module $module, Intent $intent)
    {
        // 删除权限信息
        $module->fetch('Erase', ['module' => $module->getName()]);

        $intent->ajax(true, Message::UNINSTALL_SUCCESS);
    }
}